import {
  setSleepProblem,
  scores,
  plans,
  joinPlan,
  createunifiedorder,
  daysofplan,
  daysofpressure,
  userStatus,
  getUserInfo,
  pressure,
  pressures
} from '../../api/index.js'


// pages/index/index.js
import * as echarts from '../../ec-canvas/echarts';
var xData = ["1:00", "2:00"],
  yData = [],
  chart, charts, pc = 0,
  mobile = 0;
var myChart
Page({

  /**
   * 页面的初始数据
   */
  data: {
    url: wx.getStorageSync('url'),
    gradientColor: {
      '0%': '#FFFFFF',
      '100%': '#9DC3FF'
    },
    ec: {
      onInit: function initChart(canvas, width, height) {
        myChart = echarts.init(canvas, null, {
          width: width,
          height: height
        });
        canvas.setChart(myChart);
        return myChart;
      }
    },
    //是否填写日记用来判断已经加入了计划的跳转页面
    fillInStatus: false,
    //评测状态
    showEvaluation: false,
    //是否显示推荐的睡眠计划
    showPlanRecommendation: false,
    //是否显示推荐的压力课程
    showPressureRecommendation: false,
    //是否显示继续进行计划
    showPlanProcessing: false,
    //是否显示继续进行压力课程
    showPressureProcessing:false,
    //显示更多计划
    showMore: false,
    //未登录状态
    login: false,
    //推荐计划
    recommendedPlanId: -1,
    //推荐压力课程
    recommendedPressureId: -1,
    //推荐计划的标题
    days: '',
    //推荐的计划的标题
    title: '',
    //睡眠香度
    score: '',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {

  },
  onReady: function() {
    this.getScores()
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    this.getUserStatus()
    this.getScores()
  },

  //分享
  onShareAppMessage: function() {
    return {
      title: '我正在使用SMART睡眠训练计划，超有用！推荐给你',
      imageUrl: '../../images/98875.png'

    }
  },

  getUserInfo(e) {
    getUserInfo(this);
  },

  getUserStatus() {
    userStatus().then(res => {
      console.log(res.errcode)
      if (res.errcode == '00000') {
        getApp().globalData.login = true
        this.setData({
          login: true,
        })
        let recommendedPlanId = res.recommendedPlanId
        let recommendedPressureId = res.recommendedPressureId
        this.setData({
          recommendedPlanId,
          recommendedPressureId
        })
        let planStatus = res.planStatus
        let pressureStatus = res.pressureStatus
        if ((planStatus == 1 || planStatus == 4) && (pressureStatus == 1 || pressureStatus == 4)) {
          this.setData({
            showEvaluation: true,
            showPlanRecommendation: false,
            showPressureRecommendation: false,
            showPlanProcessing: false,
            showPressureProcessing: false,
            showMore: false,
          })
        } else {
          let showEvaluation = false;
          let showPlanRecommendation = false;
          let showPressureRecommendation = false;
          let showPlanProcessing = false;
          let showPressureProcessing = false;
          let showMore = true;
          if (planStatus == 2 && recommendedPlanId != -1) {
            this.getPlans(recommendedPlanId)
            showPlanRecommendation = true;
            showPlanProcessing = false;
          }
          if (planStatus == 3) {
            showPlanProcessing = true;
            showPlanRecommendation = false;
          }
          if (pressureStatus == 2 && recommendedPressureId != -1) {
            this.getPressures(recommendedPressureId)
            showPressureRecommendation = true;
            showPressureProcessing = false;
          }
          if (pressureStatus == 3) {
            showPressureProcessing = true;
            showPressureRecommendation = false;
          }
          this.setData({
            showEvaluation,
            showPlanRecommendation,
            showPressureRecommendation,
            showPlanProcessing,
            showPressureProcessing,
            showMore,
          })
        }
      } else if (res.errcode == '00001') {
        this.setData({
          login: false
        })
        getApp().globalData.login = false;
      }
    })
  },
  getPlans(id) {
    plans(id).then(res => {
      this.setData({
        days: res.days,
        title: res.title,
        more: true,
        recommendedPlanId: id
      })
      console.log(this.data.showPlanProcessing, 'showPlanProcessing')
    })
  },
  getPressures(id) {
    console.log('getPressures:', id);
    pressures(id).then(res => {
      this.setData({

      })
    })
  },

  getWeek(date) {
    var weekDay = ["日", "一", "二", "三", "四", "五", "六"];
    var myDate = new Date(Date.parse(date));
    return weekDay[myDate.getDay()];
  },
  getScores() {
    const self = this;
    let scoreList = [];
    let weekList = [];
    scores().then(res => {
      console.log(res.errcode)
      if (res.errcode == '00000' && res.scores.length > 0) {
        res.scores.forEach((item, index) => {
          if (item.score == -1) {
            item.score = 0
          }
          if (this.getDay(-1, '-').split('-')[2] == item.date.split('-')[2] && item.score > 0) {
            console.log('已经填写过睡眠日记了' + this.getDay(-1, '-').split('-')[2] + item.date.split('-')[2] + item.score);
            console.log(item)
            this.setData({
              score: item.score,
              fillInStatus: true
            })
          }
          if (index < 7) {
            if (scoreList.length != 7) {
              scoreList.push(item.score)
              weekList.push(this.getWeek(item.date))

            }
          }
        })
        scoreList.reverse()
        weekList.reverse()
        setTimeout(() => {
          myChart.setOption({
            color: ['#3398DB'],
            tooltip: {
              trigger: 'axis',
              axisPointer: { // 坐标轴指示器，坐标轴触发有效
                type: 'shadow' // 默认为直线，可选为：'line' | 'shadow'
              }
            },
            grid: {
              left: '3%',
              right: '4%',
              top: '10%',
              bottom: '10%',
              containLabel: true
            },
            xAxis: [{
              type: 'category',

              data: weekList,
              axisLine: {
                lineStyle: {
                  color: '#7AB0FFFF',
                }
              },
              axisTick: {
                alignWithLabel: true,
                alignWithLabel: true,
                // interval: 0,
                // rotate: -30,
                // margin: -15,
                // lineStyle: { color: '#7AB0FFFF' }
              },
              axisLabel: {
                // interval: 0,
                // rotate: 40,
                color: '#999999',
                textStyle: {
                  fontSize: 10 //更改坐标轴文字大小
                }

              },

            }],
            yAxis: [{
              type: 'value',

              axisLine: {
                lineStyle: {
                  color: '#7AB0FFFF',
                }
              },
              axisLabel: {
                color: '#999999', //坐标轴文字颜色
                textStyle: {
                  fontSize: 10 //更改坐标轴文字大小
                }

              },
            }],
            series: [{
              name: '睡眠趋势',
              type: 'bar',
              barWidth: '24%',
              data: scoreList,
              itemStyle: {
                normal: {
                  //柱形图圆角，初始化效果
                  barBorderRadius: [10, 10, 0, 0],
                  color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
                    offset: 0,
                    color: 'rgba(108,165,255,1)'
                  }, {
                    offset: 1,
                    color: 'rgba(44,108,255,1)'
                  }]),
                }
              },

            }]
          });
        }, 1000)

      } else if (res.errcode == '00001') {
        this.setData({
          login: false
        })
        getApp().globalData.login = false;
        for (var i = -7; i < 0; i++) {
          weekList.push(this.getWeek(this.getDay(i, '-')))
        }
        console.log(weekList)
        setTimeout(() => {
          myChart.setOption({
            color: ['#3398DB'],
            tooltip: {
              trigger: 'axis',
              axisPointer: { // 坐标轴指示器，坐标轴触发有效
                type: 'shadow' // 默认为直线，可选为：'line' | 'shadow'
              }
            },
            grid: {
              left: '3%',
              right: '4%',
              top: '10%',
              bottom: '10%',
              containLabel: true
            },
            xAxis: [{
              type: 'category',

              data: weekList,
              axisLine: {
                lineStyle: {
                  color: '#7AB0FFFF',
                }
              },
              axisTick: {
                alignWithLabel: true,
                alignWithLabel: true,
                // interval: 0,
                // rotate: -30,
                // margin: -15,
                // lineStyle: { color: '#7AB0FFFF' }
              },
              axisLabel: {
                // interval: 0,
                // rotate: 40,
                color: '#999999',
                textStyle: {
                  fontSize: 10 //更改坐标轴文字大小
                }

              },

            }],
            yAxis: [{
              type: 'value',

              axisLine: {
                lineStyle: {
                  color: '#7AB0FFFF',
                }
              },
              axisLabel: {
                color: '#999999', //坐标轴文字颜色
                textStyle: {
                  fontSize: 10 //更改坐标轴文字大小
                }

              },
            }],
            series: [{
              name: '睡眠趋势',
              type: 'bar',
              barWidth: '24%',
              data: null,
              itemStyle: {
                normal: {
                  //柱形图圆角，初始化效果
                  barBorderRadius: [10, 10, 0, 0],
                  color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
                    offset: 0,
                    color: 'rgba(108,165,255,1)'
                  }, {
                    offset: 1,
                    color: 'rgba(44,108,255,1)'
                  }]),
                }
              },

            }]
          });
        }, 1000)
      }

    })
  },

  getDay(num, str) {
    var today = new Date();
    var nowTime = today.getTime();
    var ms = 24 * 3600 * 1000 * num;
    today.setTime(parseInt(nowTime + ms));
    var oYear = today.getFullYear();
    var oMoth = (today.getMonth() + 1).toString();
    if (oMoth.length <= 1) oMoth = '0' + oMoth;
    var oDay = today.getDate().toString();
    if (oDay.length <= 1) oDay = '0' + oDay;
    return oYear + str + oMoth + str + oDay;
  },


  getMore() {
    wx.navigateTo({
      url: '/pages/more-course/more-course',
    })

  },


  addPlan() {
    let data = {
      planId: this.data.recommendedPlanId
    }
    joinPlan(data).then(res => {
      if (res.errcode == '00000') {
        let userPlanId = res.userPlanId
        if (res.price == 0) {
          wx.navigateTo({
            url: '/pages/schedule/schedule',
          })
        } else if (res.price > 0) {
          let data = {
            userPlanId: userPlanId
          }
          createunifiedorder(data).then(res => {
            wx.requestPayment({
              timeStamp: res.timeStamp,
              nonceStr: res.nonceStr,
              package: res.package,
              signType: res.signType,
              paySign: res.paySign,
              success(res) {
                if (res.errMsg == 'requestPayment:ok') {
                  wx.reLaunch({
                    url: '/pages/schedule/schedule',
                  })
                } else {
                  wx.showToast({
                    title: '支付失败',
                    icon: 'none'
                  })
                }
              },
              fail(res) {}
            })
          })
        }
      }
    })
  },

  //打开计划
  openPlan() {
    if (this.data.fillInStatus) {
      daysofplan().then(res => {
        if (res.errcode = '00000') {
          wx.setStorageSync('entity', res.days.find(day => day.id === res.currentDayId))
          wx.reLaunch({
            url: '/pages/course/course',
          })
        }
      })
    } else {
      wx.navigateTo({
        url: '/pages/schedule/schedule',
      })
    }
  },




  handleChange(e) {
    let data = {
      sleepProblem: e.currentTarget.dataset.value
    }
    setSleepProblem(data).then(res => {
      if (res.errcode == '00000') {
        if (res.problemType == 'sleep') {
          wx.navigateTo({
            url: '/pages/ais-evaluation/ais-evaluation'
          })
        } else {
          wx.navigateTo({
            url: '/pages/pressure-evaluation/pressure-evaluation'
          })
        }
      }
    })
  },

  //登录
  handleLogin(e) {
    getUserInfo(this)
  },

  // 继续进行睡眠计划
  handlePlanProcessing() {
    daysofplan().then(res => {
      if (res.errcode = '00000') {
        wx.setStorageSync('entity', res.days.find(day => day.id === res.currentDayId))
        if (this.data.fillInStatus) {
          wx.navigateTo({
            url: '/pages/course/course'
          })
        } else {
          wx.navigateTo({
            url: '/pages/schedule/schedule'
          })

        }
      }
    })
  },

  // 继续进行压力课程
  handlePressureProcessing() {
    daysofpressure().then(res => {
      if (res.errcode = '00000') {
        wx.setStorageSync('entity', res.days.find(day => day.id === res.currentDayId))
        if (this.data.fillInStatus) {
          wx.navigateTo({
            url: '/pages/pressure/pressure'
          })
        } else {
          wx.navigateTo({
            url: '/pages/pressure-schedule/pressure-schedule'
          })
        }
      }
    })
  },

  // 推荐的睡眠计划
  handlePlanDetail() {
    wx.navigateTo({
      url: '/pages/course-description/course-description?planId=' + this.data.recommendedPlanId,
    })

  },

  // 推荐的压力课程
  handlePressureDetail() {
    wx.navigateTo({
      url: '/pages/pressure-description/pressure-description?pressureId=' + this.data.recommendedPressureId,
    })

  },

})